<?php

namespace app\admin\controller\autokeyword;

use app\common\controller\Backend;
use think\Exception;

/**
 * 全局配置管理
 *
 * @icon fa fa-circle-o
 */
class Config extends Backend
{
    
    /**
     * AutokeywordConfig模型对象
     * @var \app\admin\model\AutokeywordConfig
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AutokeywordConfig;
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list = [];

        foreach ($this->model->select() as $key => $val) {
            $val = $val->toArray();

            if ($val['content']) {
                $val['content'] = json_decode($val['content'], true);
            }

            $list[$val['position']][] = $val;
        }

        $this->view->assign('list', $list);

        $positionList = [
            'admin' => '后台设置',
            'index' => '前台设置'
        ];

        $this->view->assign('positionList', $positionList);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $this->token();

                $configList = [];

                reset($params);
                $key     = key($params);
                $params  = array_shift($params);

                foreach ($this->model->all() as $v) {

                    if (intval($v['position']) === $key && isset($params[$v['key']])) {
                        $value = $params[$v['key']];
                        $v['value'] = $value;
                        $configList[] = $v->toArray();
                    }

                }

                try {
                    $this->model->allowField(true)->saveAll($configList);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }
}
